import { useUserinfo } from "@/stores/userinfo"

export const permission = {
    mounted(el:HTMLElement, binding:{value:string[]}) {
        console.log("Permission directive mounted")
        console.log("Required permissions:", binding.value)
        const loginData = localStorage.getItem('login')
        console.log("Raw login data:", loginData)

        if(loginData) {
            try {
                const parsed = JSON.parse(loginData)
                console.log("Parsed login data:", parsed)
                let userPermissions = []
                if(parsed.scopes) {
                    userPermissions = parsed.scopes
                    console.log("Using scopes:", userPermissions)
                } else if(parsed.permissions) {
                    userPermissions = parsed.permissions
                    console.log("Using permissions:", userPermissions)
                } else {
                    if(parsed.role === 'admin' || parsed.role === 'editor') {
                        userPermissions = ['write', 'read']
                        console.log("Admin/editor role detected")
                    } else if(parsed.type === 1) {
                        userPermissions = ['write', 'read']
                        console.log("Admin type (1) detected")
                    } else {
                        userPermissions = ['read']
                        console.log("Default read-only permissions")
                    }
                }
                const hasPermission = binding.value.some(permission => 
                    userPermissions.includes(permission)
                )

                if(!hasPermission) {
                    console.log("Permission check failed, removing element")
                    el.parentNode?.removeChild(el)
                } else {
                    console.log("Permission check passed")
                }
            } catch (e) {
                console.error("Error parsing login data:", e)
                console.log("Error parsing login data, removing element for safety")
                el.parentNode?.removeChild(el)
            }
        } else {
            console.log("No login data found, removing element")
            el.parentNode?.removeChild(el)
        }
    }
}


